package com.lwei.tallybook.client.filter;

import cn.hutool.extra.servlet.ServletUtil;
import com.lwei.tallybook.base.domain.Account;
import com.lwei.tallybook.client.config.SpringSupport;
import com.lwei.tallybook.client.controller.HomeController;
import com.lwei.tallybook.client.enums.ServletEnum;
import com.lwei.tallybook.service.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.lwei.tallybook.client.enums.ServletEnum.SESSION_CURRENT;
import static com.lwei.tallybook.client.enums.ServletEnum.SESSION_CURRENT_NAME;

/**
 * 登录拦截器
 * @author sks.lwei
 */
@Deprecated
public class LoginFilter implements Filter {

    private static final String TO_LOGIN_PATH = "/login";
    private static final String LOGIN_PATH = "/api/home/login";

    private static final String STATIC_PATH = "/static";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUri = request.getRequestURI();

        if(requestUri.startsWith(STATIC_PATH) || TO_LOGIN_PATH.equals(requestUri) || LOGIN_PATH.equals(requestUri)){
            filterChain.doFilter(request, response);
            return;
        }

        Cookie cookieLogin = ServletUtil.getCookie(request, ServletEnum.COOKIE_LOGIN.name());
        if(cookieLogin == null || StringUtils.isBlank(cookieLogin.getValue())){
            response.sendRedirect(TO_LOGIN_PATH);
            return;
        }

        HttpSession session = request.getSession();
        Object sessionLogin = session.getAttribute(ServletEnum.SESSION_CURRENT.name());
        if(sessionLogin == null){
            Assert.notNull(cookieLogin.getValue(), "cookie is null");
            //自动登录
            AccountService accountService = SpringSupport.getBean(AccountService.class);
            Account account = accountService.getAccountByUuid(cookieLogin.getValue());
            session.setAttribute(SESSION_CURRENT.name(), account);
            session.setAttribute(SESSION_CURRENT_NAME.name(), account.getUserName());
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
